package al.xc.common.util;

import java.util.HashMap;
import java.util.Map;

/**
 * query 参数 he map 互转换
 */
public class UrlParamMapUtils {
    /**
     * 请求参数转为map
     * @param value
     * @return
     */
    public static Map<String, Object> transforToMap(String value) {
        Map<String, Object> result = new HashMap<>();
        if (null == value || value.trim().equals("")) {
            return result;
        }
        String[] split = value.split("&");
        for (int i  = 0;i < split.length; ++i) {
            String[] kv = split[i].split("=");
            if (2 == kv.length) {
                result.put(kv[0], kv[1]);
            }
        }
        return result;
    }

    /**
     * map 转为 请求 参数
     * @param map
     * @return
     */
    public static String transforToUrlParam(Map<String, Object> map) {
        if (null == map) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        String result = sb.toString();
        if (result.endsWith("&")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }
}
